package com.zhongzhi.javafx.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import com.zhongzhi.common.Common;
import com.zhongzhi.springboot.pojo.MeasureShow;
import com.zhongzhi.springboot.pojo.MeasureTabShow;
import com.zhongzhi.springboot.pojo.StationShow;
import com.zhongzhi.util.ClientUtil;
import com.zhongzhi.util.JsonResult;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;

import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import lombok.extern.log4j.Log4j;
import javafx.scene.control.MenuItem;

import javafx.scene.control.MenuButton;

import javafx.scene.control.DatePicker;
@Log4j
public class ExcelController implements Initializable{
	@FXML
	private DatePicker startTime;		//开始时间
	@FXML
	private DatePicker endTime;			//结束时间
	@FXML
	private MenuButton station;			//工位
	@FXML
	private MenuItem all;				//
	@FXML
	private TextField Menum;			//机号
	@FXML
	private TextField fileName;			//文件名
	@FXML
	private TextField folder;			//文件夹路径
	@FXML
	private Button selectFolder;		//文件夹选择器
	@FXML
	private Button end;					//取消
	@FXML
	private Button add;					//确定

	private Integer stationId = null;

	private List<MeasureShow> jsonlist = null;
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		log.info("数据导出窗口:开始初始化");
		//初始化工位查询
		station();

		//选择全部
		all.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				station.setText("全部工位");
				stationId=null;
			}
		});

		selectFolder.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				DirectoryChooser directoryChooser=new DirectoryChooser();
				File file = directoryChooser.showDialog(new Stage());
				String path = file.getPath();//选择的文件夹路径
				folder.setText(path);
			}
		});


		//工位选择
		station.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				station();

			}
		});
		//取消
		end.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				Stage window = (Stage) end.getScene().getWindow();
				window.close();
			}
		});
		//导出
		add.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				//导出数据
				excel();
			}


		});

		log.info("数据导出窗口:初始化完成");

	}

	/**
	 * 开始时间转为时间戳
	 * @return
	 */
	private Long statrTimeLong() {
		LocalDate value = startTime.getValue();
		if (value==null || value.equals("")) {
			return null;
		}
		String string = value.toString();
		if (string==null || string.equals("")) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(string).getTime()-24L*60*60*1000;
		} catch (ParseException e) {
			log.error("数据导出窗口:开始时间转为时间戳失败:"+e);
		}
		return null;
	}

	/**
	 * 结束转为时间戳
	 * @return
	 */
	private Long endTimeLong() {
		LocalDate value = endTime.getValue();
		if (value==null || value.equals("")) {
			return null;
		}
		String string = value.toString();
		if (string==null || string.equals("")) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(string).getTime()+24L*60*60*1000;
		} catch (ParseException e) {
			log.error("数据导出窗口:结束时间转为时间戳失败:"+e);
		}
		return null;
	}
	/**工位查询*/
	private void station() {
		try {
			String s = "http://127.0.0.1:8080/station/select?pages=1&line=1000";
			log.info("导出数据窗口:发起查询工位请求"+s);
			String stationString = ClientUtil.Gethttp(s);
			log.info("导出数据窗口:获得查询工位结果"+stationString);
			JsonResult jsonobj = ClientUtil.Jsonobj(stationString, JsonResult.class);
			String string = jsonobj.getData().toString();
			List<StationShow> stationlist = ClientUtil.Jsonlist(string, StationShow.class);
			for (StationShow stationShow : stationlist) {
				MenuItem item = new MenuItem(stationShow.getStationname());
				item.setOnAction(new EventHandler<ActionEvent>() {

					@Override
					public void handle(ActionEvent event) {
						station.setText(stationShow.getStationname());
						stationId = stationShow.getId();
					}
				});
				this.station.getItems().add(item);
			}
		} catch (Exception e) {
			log.error("导出数据窗口:获得查询工位结果失败:"+e);
		}
		
	}

	//执行分页查询
	private void insert(Integer pages,Integer line) {
		try {
			String httpstring = "http://127.0.0.1:8080/measure/select?pages="+pages+"&line="+line;
			log.info("导出数据窗口:发起分页查询请求"+httpstring);
			Long statrTimeLong = statrTimeLong();
			Long endTimeLong = endTimeLong();
			String text = Menum.getText();

			if (text==null||text.equals("")) {
				text=null;
			}
			if (statrTimeLong!=null) {
				httpstring=httpstring+"&startTime="+statrTimeLong;
			}
			if (endTimeLong!=null) {
				httpstring=httpstring+"&endTime="+endTimeLong;
			}
			if (stationId!=null) {
				httpstring=httpstring+"&StationId="+stationId;
			}
			if (text!=null && text.equals("")!=true) {
				httpstring=httpstring+"&str="+text;
			}

			String gethttp = ClientUtil.Gethttp(httpstring);
			log.info("导出数据窗口:获取分页查询结果"+gethttp);
			JsonResult jsonobj = ClientUtil.Jsonobj(gethttp, JsonResult.class);
			String string = jsonobj.getData().toString();
			jsonlist = ClientUtil.Jsonlist(string, MeasureShow.class);
		} catch (Exception e) {
			log.error("导出数据窗口:获取分页查询结果失败"+e);
		}
		
	}
	//导出表格
	private void excel() {
		// TODO Auto-generated method stub
		
		insert(1,2000000);
		
		//获取一个excel
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
		//获取一个表格
		HSSFSheet sheet = hssfWorkbook.createSheet("数据记录表");
		//获取表头
		HSSFRow createRow = sheet.createRow(0);
		//设置单元格居中
		HSSFCellStyle createCellStyle = hssfWorkbook.createCellStyle();
		createCellStyle.setAlignment(HorizontalAlignment.CENTER);

		//设置列名
		HSSFCell createCell = createRow.createCell(0);
		createCell.setCellValue("ID");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(1);
		createCell.setCellValue("机号");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(2);
		createCell.setCellValue("机型");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(3);
		createCell.setCellValue("开始时间");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(4);
		createCell.setCellValue("结束时间");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(5);
		createCell.setCellValue("工位");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(6);
		createCell.setCellValue("据a下沉量");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(7);
		createCell.setCellValue("数据a开始高度");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(8);
		createCell.setCellValue("数据b下沉量");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(9);
		createCell.setCellValue("数据b开始高度");
		createCell.setCellStyle(createCellStyle);

		createCell = createRow.createCell(10);
		createCell.setCellValue("本次测量备注");
		createCell.setCellStyle(createCellStyle);

		//添加内容到表格
		if (jsonlist!=null && jsonlist.size()!=0) {
			for (int i = 0; i < jsonlist.size(); i++) {
				createRow = sheet.createRow(i + 1);
				MeasureShow measure = jsonlist.get(i);
				MeasureTabShow measureShow = new MeasureTabShow(measure);

				createCell = createRow.createCell(0);
				createCell.setCellValue(measureShow.getId());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(1);
				createCell.setCellValue(measureShow.getDeviceNum());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(2);
				createCell.setCellValue(measureShow.getTypeName());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(3);
				createCell.setCellValue(measureShow.getStartTime());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(4);
				createCell.setCellValue(measureShow.getEndTime());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(5);
				createCell.setCellValue(measureShow.getStationName());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(6);
				createCell.setCellValue(measureShow.getSinkA());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(7);
				createCell.setCellValue(measureShow.getStartAltitudeA());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(8);
				createCell.setCellValue(measureShow.getSinkB());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(9);
				createCell.setCellValue(measureShow.getStartAltitudeB());
				createCell.setCellStyle(createCellStyle);

				createCell = createRow.createCell(10);
				createCell.setCellValue(measureShow.getRemarks());
				createCell.setCellStyle(createCellStyle);

			}
		}
		String dolserPath = folder.getText();
		if (dolserPath==null || dolserPath.equals("")) {
			dolserPath="D:\\doosan\\Excel";
		}
		File file = new File(dolserPath);
		if (file.exists()==false) {
			file.mkdirs();
		}
		String filename = fileName.getText();
		if (filename==null || filename.equals("")) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
			Date date = new Date(System.currentTimeMillis());
			
			filename="斗山下沉量测量数据"+format.format(date);
		}
		filename="\\"+filename+".xls";
		Stage window = (Stage) end.getScene().getWindow();
		window.close();
		try {
			OutputStream outputStream = new FileOutputStream(dolserPath+filename);
			hssfWorkbook.write(outputStream);
			outputStream.close();
		} catch (Exception e) {
			log.error("数据导出窗口:导出数据失败:"+e);
		}
		

	}
	
	

}
